package org.base.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;

/**
 * 获取地址类
 *
 * @author ruoyi
 */
@Slf4j
public class AddressUtils {

//    public static final String IP_URL = "http://ip.taobao.com/service/getIpInfo.php";

    // private static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=%s";
    private static final String IP_URL = "http://ip-api.com/json/%s?lang=zh-CN";

    public static String getRealAddressByIP(String ip) {
        String address = "XX XX";
        // 内网不查询
        if (IpUtils.internalIp(ip)) {
            return "内网IP";
        }

        final RestTemplate restTemplate = new RestTemplate();
        String url = String.format(IP_URL, ip);
        final ResponseEntity<String> entity = restTemplate.postForEntity(url, null, String.class);
        final HttpStatus statusCode = entity.getStatusCode();
        if (statusCode == HttpStatus.OK) {
            final String body = entity.getBody();
            log.debug(body);
            final ObjectMapper objectMapper = new ObjectMapper();
            try {
                final HashMap hashMap = objectMapper.readValue(body, HashMap.class);
                Object region = hashMap.get("regionName");
                Object city = hashMap.get("city");
                address = region + " " + city;
                return address;
            } catch (JsonProcessingException e) {
                log.warn(e.getMessage(), e);
            }
        }
        return null;
    }
}
